package org.example.springweibo.service;

import org.example.springweibo.exception.ServiceException;
import org.example.springweibo.mapper.UserMapper;
import org.example.springweibo.pojo.entity.User;
import org.example.springweibo.serviceode.ServiceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 业务层
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    public int regUser(User user) {
        String isEmptyStr="";
        if (isEmptyStr.equals(user.getUsername()) || user.getUsername()==null ||
                isEmptyStr.equals(user.getPassword()) || user.getPassword() == null ||
                isEmptyStr.equals(user.getNickname()) || user.getNickname() ==null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"参数输入错误");
        }

        List<User> users = userMapper.selectUserDataByUsername(user);
        if (!users.isEmpty()){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"用户名已存在");
        }

        //密码加密
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setCreated(new Date());
        return userMapper.insertUserData(user);
    }

    public User loginUser(User user){
        String isEmptyStr="";
        if (isEmptyStr.equals(user.getUsername()) || user.getUsername() ==null ||
                isEmptyStr.equals(user.getPassword()) || user.getPassword() == null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"参数输入错误");
        }

        List<User> users = userMapper.selectUserDataByUsername(user);
        if (users.isEmpty()){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"用户未注册");
        }

        User userData = new User();
        boolean isT = false;

        for (User user1 : users) {
            if (user1.getUsername().equals(user.getUsername())){
                if (user1.getPassword().length()>20 &&
                        new BCryptPasswordEncoder().matches(user.getPassword(),user1.getPassword())){
                    userData = user1;
                    isT = true;
                }else if (user1.getPassword().length()<=20 && user1.getPassword().equals(user.getPassword())){
                    userData = user1;
                    isT = true;
                }
            }
        }

        if (!isT) {
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"用户或密码错误");
        }

        userData.setPassword(null);

        return userData;
    }


}
